package com.information.manage.basic.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Initial Heart
 * Date: 2022-03-06.
 * Description:  类转换工具  转换具有相同属性的字段值
 * Version: V1.0
 */
public class ConvertUtils {

    private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetList;
    }

    public static <T> T sourceToTargetIfNotNull(Object source, Class<T> targetClass) {
        try {
            // 创建目标类的一个实例
            T target = targetClass.getDeclaredConstructor().newInstance();

            // 获取 source 和 target 类的所有字段（包括继承的字段）
            Field[] sourceFields = source.getClass().getDeclaredFields();
            Field[] targetFields = targetClass.getDeclaredFields();

            // 保存 target 的所有字段名
            Set<String> targetFieldNames = new HashSet<>();
            for (Field field : targetFields) {
                targetFieldNames.add(field.getName());
            }

            for (Field sourceField : sourceFields) {
                // 设置为可访问，因为字段可能是私有的
                sourceField.setAccessible(true);

                String fieldName = sourceField.getName();
                // 检查 target 是否也有这个字段
                if (targetFieldNames.contains(fieldName)) {
                    Field targetField = targetClass.getDeclaredField(fieldName);
                    targetField.setAccessible(true);

                    // 获取 source 字段的值
                    Object value = sourceField.get(source);

                    // 如果值不为空，则复制到 target
                    if (value != null && !Objects.equals(value, "")) {
                        targetField.set(target, value);
                    }
                }
            }

            return target;
        } catch (Exception e) {
            throw new RuntimeException("Error copying fields", e);
        }
    }
}